<!-- 医生管理 -->
<template>
  <PageContainer title="医生管理">
    <!-- 搜索和操作区 -->
    <div class="search-operate">
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input v-model="searchForm.keyword" placeholder="请输入医生姓名/手机号搜索" prefix-icon="el-icon-search"
            class="search-input"></el-input>
        </el-col>
        <el-col :span="8">
          <el-select v-model="searchForm.hospitalId" placeholder="请选择所属医院" class="hospital-select">
            <el-option label="全部" value=""></el-option>
            <el-option v-for="item in hospitalList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-col>
        <el-col :span="6" class="operate-buttons">
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i> 添加医生
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 医生表格 -->
    <el-table :data="doctorList" border stripe :loading="loading" style="width: 100%; margin-top: 20px;">
      <el-table-column label="医生ID" prop="id" width="80" align="center"></el-table-column>
      <el-table-column label="医生头像" width="100" align="center">
        <template #default="scope">
          <el-image :src="scope.row.avatar || defaultAvatar"
            style="width: 50px; height: 50px; border-radius: 50%; object-fit: cover;" fit="cover"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="医生姓名" prop="realName" width="120"></el-table-column>
      <el-table-column label="所属医院" prop="hospitalName" width="180"></el-table-column>
      <el-table-column label="专业领域" prop="specialty" width="180"></el-table-column>
      <el-table-column label="手机号" prop="phone" width="130" align="center"></el-table-column>
      <el-table-column label="职称" prop="title" width="120" align="center">
        <template #default="scope">
          <el-tag type="primary">{{ scope.row.title || '无' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleViewDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <TablePagination :total="total" :page-size="pageSize" :current-page="currentPage" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" style="margin-top: 20px; text-align: right;"></TablePagination>

    <!-- 添加/编辑医生弹窗 -->
    <el-dialog :title="isEdit ? '编辑医生' : '添加医生'" :visible.sync="dialogVisible" width="600px"
      :before-close="handleDialogClose">
      <el-form :model="form" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="医生姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入医生姓名"></el-input>
        </el-form-item>
        <el-form-item label="所属医院" prop="hospitalId">
          <el-select v-model="form.hospitalId" placeholder="请选择所属医院">
            <el-option v-for="item in hospitalList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业领域" prop="specialty">
          <el-input v-model="form.specialty" placeholder="请输入专业领域（如：宠物外科）"></el-input>
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-input v-model="form.title" placeholder="请输入职称（如：主治医师）"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" type="email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="医生简介" prop="introduction">
          <el-input v-model="form.introduction" type="textarea" :rows="5" placeholder="请输入医生简介"></el-input>
        </el-form-item>
        <el-form-item label="执业证书" prop="certificate">
          <el-upload class="upload-demo" :action="uploadUrl" :on-success="handleCertificateUpload"
            :before-upload="handleBeforeUpload" :file-list="certificateFileList" list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="医生头像" prop="avatar">
          <el-upload class="upload-demo" :action="uploadUrl" :on-success="handleAvatarUpload"
            :before-upload="handleBeforeUpload" :file-list="avatarFileList" list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="form.status" active-value="1" inactive-value="0" active-text="启用"
            inactive-text="禁用"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleFormSubmit">确定</el-button>
      </template>
    </el-dialog>
  </PageContainer>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import PageContainer from '@/components/common/PageContainer.vue'
import TablePagination from '@/components/common/TablePagination.vue'
import { getDoctorList, addDoctor, editDoctor, updateDoctorStatus } from '@/api/doctor'
import { getHospitalList } from '@/api/hospital'
// 搜索表单
const searchForm = reactive({
  keyword: '',
  hospitalId: ''
})

// 表格数据
const doctorList = ref([])
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)
const loading = ref(false)

// 医院列表
const hospitalList = ref([])

// 弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const uploadUrl = import.meta.env.VITE_UPLOAD_URL || '/api/upload'

// 文件列表
const certificateFileList = ref([])
const avatarFileList = ref([])

// 表单数据
const form = reactive({
  id: '',
  realName: '',
  hospitalId: '',
  specialty: '',
  title: '',
  phone: '',
  email: '',
  introduction: '',
  certificate: '',
  avatar: '',
  status: 1
})

// 表单校验规则
const formRules = reactive({
  realName: [
    { required: true, message: '请输入医生姓名', trigger: 'blur' }
  ],
  hospitalId: [
    { required: true, message: '请选择所属医院', trigger: 'change' }
  ],
  specialty: [
    { required: true, message: '请输入专业领域', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  certificate: [
    { required: true, message: '请上传执业证书', trigger: 'change' }
  ]
})

// 获取医院列表
const fetchHospitalList = async () => {
  try {
    const res = await getHospitalList()
    hospitalList.value = res.data
  } catch (error) {
    ElMessage.error('获取医院列表失败')
  }
}

// 获取医生列表
const fetchDoctorList = async () => {
  try {
    loading.value = true
    const res = await getDoctorList({
      keyword: searchForm.keyword,
      hospitalId: searchForm.hospitalId,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    doctorList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取医生列表失败')
  } finally {
    loading.value = false
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchDoctorList()
}

// 页码改变
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchDoctorList()
}

// 添加医生
const handleAdd = () => {
  isEdit.value = false
  // 重置表单
  form.id = ''
  form.realName = ''
  form.hospitalId = ''
  form.specialty = ''
  form.title = ''
  form.phone = ''
  form.email = ''
  form.introduction = ''
  form.certificate = ''
  form.avatar = ''
  form.status = 1
  certificateFileList.value = []
  avatarFileList.value = []
  dialogVisible.value = true
}

// 编辑医生
const handleEdit = (row) => {
  isEdit.value = true
  // 填充表单
  form.id = row.id
  form.realName = row.realName
  form.hospitalId = row.hospitalId
  form.specialty = row.specialty
  form.title = row.title
  form.phone = row.phone
  form.email = row.email
  form.introduction = row.introduction
  form.certificate = row.certificate
  form.avatar = row.avatar
  form.status = row.status
  // 图片列表
  certificateFileList.value = row.certificate ? [{ url: row.certificate }] : []
  avatarFileList.value = row.avatar ? [{ url: row.avatar }] : []
  dialogVisible.value = true
}

// 查看医生详情
const handleViewDetail = (row) => {
  console.log('医生详情:', row)
  ElMessage.info('查看医生详情功能')
  // 实际项目中可以打开详情弹窗或跳转到详情页
}

// 改变医生状态
const handleStatusChange = async (row) => {
  try {
    await updateDoctorStatus({
      id: row.id,
      status: row.status
    })
    ElMessage.success(`医生已${row.status === 1 ? '启用' : '禁用'}`)
  } catch (error) {
    // 失败时回滚状态
    row.status = row.status === 1 ? 0 : 1
    ElMessage.error('状态更新失败')
  }
}

// 表单提交
const handleFormSubmit = async () => {
  try {
    await formRef.value.validate()
    if (isEdit) {
      // 编辑医生
      await editDoctor(form)
      ElMessage.success('编辑医生成功')
    } else {
      // 添加医生
      await addDoctor(form)
      ElMessage.success('添加医生成功')
    }
    dialogVisible.value = false
    fetchDoctorList()
  } catch (error) {
    ElMessage.error(isEdit ? '编辑医生失败' : '添加医生失败')
  }
}

// 执业证书上传成功
const handleCertificateUpload = (response) => {
  form.certificate = response.data.url
  certificateFileList.value = [{ url: response.data.url }]
}

// 头像上传成功
const handleAvatarUpload = (response) => {
  form.avatar = response.data.url
  avatarFileList.value = [{ url: response.data.url }]
}

// 上传图片前校验
const handleBeforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('请上传图片文件')
    return false
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB')
    return false
  }
  return true
}

// 关闭弹窗
const handleDialogClose = () => {
  formRef.value?.resetFields()
  certificateFileList.value = []
  avatarFileList.value = []
  dialogVisible.value = false
}

// 页面挂载时获取数据
onMounted(() => {
  fetchHospitalList()
  fetchDoctorList()
})
</script>

<style scoped lang="scss">
.search-operate {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;

  .search-input {
    width: 100%;
  }

  .hospital-select {
    width: 100%;
  }

  .operate-buttons {
    display: flex;
    justify-content: flex-end;
  }
}

:deep(.el-upload--picture-card) {
  width: 100px;
  height: 100px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}
</style>